<template>
    <div class="invoiceform">
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
            :size="'default'"
            status-icon
        >
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="销售方" prop="from_corp_nam">
                        <el-autocomplete
                        v-model="formData.from_corp_nam"
                        :fetch-suggestions="queryFromCorpSearch as unknown as AutocompleteFetchSuggestions"
                        :trigger-on-focus="false"
                        clearable
                        placeholder="请输入"
                    />
                        
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="购买方" prop="to_corp_nam">
                        <el-autocomplete
                        v-model="formData.to_corp_nam"
                        :fetch-suggestions="queryToCorpSearch as unknown as AutocompleteFetchSuggestions"
                        :trigger-on-focus="false"
                        clearable
                        placeholder="请输入"
                    />
                        
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="发票号" prop="invoice_no">
                        <el-input v-model.trim="formData.invoice_no" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="发票代码" prop="invoice_cod">
                        <el-input v-model.trim="formData.invoice_cod" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="货币" prop="currency_cod">
                        <el-select
                            v-model="formData.currency_cod"
                            :clearable="true"
                        >
                            <el-option
                                v-for="optValue in currency"
                                :key="optValue.value"
                                :label="optValue.label"
                                :value="optValue.value"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="开票日期" prop="invoice_date">
                        <el-date-picker
                            v-model="formData.invoice_date"
                            type="date"
                            :size="'default'"
                        />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="2">
                <el-col :span="4">
                    <el-form-item label="未税价" prop="cost_amount">
                        <el-input-number
                            :min="0"
                            v-model="formData.cost_amount"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="税率" prop="tax_rate">
                        <el-input-number :min="0" v-model="formData.tax_rate" />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="税额" prop="tax_amount">
                        <el-input-number
                            :min="0"
                            v-model="formData.tax_amount"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="4">
                    <el-form-item label="金额" prop="amount">
                        <el-input-number :min="0" v-model="formData.amount" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
    <div class="detailtable">
        <el-table
            ref="tableRef"
            :data="formData.details"
            row-key="id"
            table-layout="auto"
            @row-dblclick="onDetailDbClick"
        >
            <template #empty>
                <span>无数据</span>
            </template>
            <el-table-column
                v-bind:align="'center'"
                prop="cntr_typ"
                label="Type"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model.trim="scope.row.cntr_typ" />
                    </template>
                    <template v-else>
                        {{ scope.row.cntr_typ }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="status"
                label="Status"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model.trim="scope.row.status" />
                    </template>
                    <template v-else>
                        {{ scope.row.status }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="description"
                label="Description"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model.trim="scope.row.description" />
                    </template>
                    <template v-else>
                        {{ scope.row.description }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column
                v-bind:align="'center'"
                prop="qty"
                label="Qty"
                width="100"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model.number="scope.row.qty" />
                    </template>
                    <template v-else>
                        {{ scope.row.qty }}
                    </template>
                </template>
            </el-table-column>

            <el-table-column
                v-bind:align="'center'"
                prop="price"
                label="Price/Unit"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input v-model.trim="scope.row.price" />
                    </template>
                    <template v-else>
                        {{ scope.row.price }}
                    </template>
                </template>
            </el-table-column>

            <el-table-column
                v-bind:align="'center'"
                prop="amount"
                label="Total Price"
                width="180"
            >
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-input-number
                            v-model.number="scope.row.amount"
                            :min="0"
                        ></el-input-number>
                    </template>
                    <template v-else>
                        {{ scope.row.amount }}
                    </template>
                </template>
            </el-table-column>
            <el-table-column>
                <template #default="scope">
                    <template v-if="scope.row.isEdit">
                        <el-button
                            size="small"
                            type="primary"
                            @click="onEdit(scope.$index, scope.row)"
                            >确定</el-button
                        >
                        <el-button
                            size="small"
                            type="info"
                            @click="onCancel(scope.$index, scope.row)"
                            >取消</el-button
                        >
                        <el-button
                            size="small"
                            type="warning"
                            @click="onDel(scope.$index)"
                            >删除</el-button
                        >
                    </template>
                </template>
            </el-table-column>
        </el-table>
    </div>
    <div class="btn-group">
        <el-button-group>
            <el-button
                class="btn"
                type="primary"
                v-debounce="save"
                size="large"
            >
                保存
            </el-button>
            <el-button class="btn" type="primary" @click="reset" size="large"
                >重置</el-button
            >

            <el-button
                class="btn"
                type="primary"
                @click="addDetail"
                size="large"
                >增加明细</el-button
            >
            
        </el-button-group>
    </div>
</template>
<script setup lang="ts" name="Invoice">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import {
AutocompleteFetchSuggestions,
    ElMessage,
    type FormInstance,
    type FormRules,
    type TableRefs,
} from 'element-plus';
import type { InvoiceModel, InvoiceDetailModel } from '@/common/types/business';

import { Request } from '@/app/request';
import { useAppStore } from '@/store/app';
import { isNil, omit, template } from 'lodash';
import { ValidateFieldsError } from 'async-validator';
const { currency } = storeToRefs(useAppStore());

const formRef = ref<FormInstance>();
const formData = reactive<InvoiceModel>({});
const tableRef = ref<TableRefs>();
// const tableData = reactive<InvoiceDetailModel[]>([]);
const props = defineProps<{
    data: InvoiceModel;
}>();
const emit = defineEmits<{
    create: [action: InvoiceModel];
    update: [action: InvoiceModel];
    close: [];
}>();
/* const aaa = async (queryString: string, callback: any) => {

} */
const queryFromCorpSearch = async  (queryString: string, cb: (arg: any) => void)  => {
    const req = new Request('过滤发票户头名称', {type: 'from', queryString});
    const r = await req.post();
    if (r.code > 100) {
        cb(r.obj);
    } else {
        cb([]);
    }
};
const queryToCorpSearch = async (queryString: string, cb: (arg: any) => void) => {
    const req = new Request('过滤发票户头名称', {type: 'to', queryString});
    const r = await req.post();
    if (r.code > 100) {
        cb(r.obj);
    } else {
        cb([]);
    }
};
const rules = reactive<FormRules>({
    from_corp_nam: [
        { required: true, message: '销售方不能为空', trigger: 'blur' },
    ],
    to_corp_nam: [
        { required: true, message: '购买方不能为空', trigger: 'blur' },
    ],
    currency_cod: [{ required: true, message: '请输入货币', trigger: 'blur' }],

    invoice_no: [{ required: true, message: '请输入发票号', trigger: 'blur' }],
    /*invoice_cod: [
        { required: true, message: '请输入发票代码', trigger: 'blur' },
    ],*/
    invoice_date: [
        { required: true, message: '请输入发票日期', trigger: 'blur' },
    ],
    /* tax_no: [{ required: true, message: '请输入税号', trigger: 'blur' }], */
    cost_amount: [
        { required: true, message: '请输入非含税价', trigger: 'blur' },
    ],
    tax_rate: [{ required: true, message: '请输入税率', trigger: 'blur' }],
    tax_amount: [{ required: true, message: '请输入税额', trigger: 'blur' }],
    amount: [{ required: true, message: '金额不能为空', trigger: 'blur' }],
});

let temDetail: any;

const reset = () => {
    formRef.value?.resetFields();
    if (formData.details) {
        formData.details!.length = 0;
    }
};

onMounted(() => {
    reset();
    if (props.data) {
        //修改
        Object.assign(formData, props.data);
    }
});
const save = async () => {
    const formValid = await formRef.value?.validate(
        (isValid: boolean, _invalidFields?: ValidateFieldsError) => {
            // return isValid;
            return;
        },
    );

    if (formValid) {
        if (formData.details) {
            for (let index = 0; index < formData.details?.length; index++) {
            const element = formData.details![index];

            if (element.isEdit) {
                ElMessage({
                    type: 'info',
                    dangerouslyUseHTMLString: true,
                    message: '存在未保存明细',
                });
                return;
            }
        }
        }
        
        if (props.data.id) {
            // 修改
            // const param = toValue(formData);
            // param['details'] = toValue(tableData);
            const req = new Request('发票修改', formData);
            const r = await req.post();
            if (r.code > 100) {
                emit('update', r.obj as InvoiceModel);
                // reset();
                return true;
            }
        } else {
            // 增加
            const param = omit(formData, ['id']);
            // param['details'] = toValue(tableData);
            const req = new Request('发票增加', param);
            const r = await req.post();
            if (r.code > 100) {
                emit('create', r.obj as InvoiceModel);
                reset();
                return true;
            }
        }
    } else {
        return false;
    }
};
const addDetail = () => {
    if (!formData.details) {
        formData.details = [];
    }
    formData.details.push({
        isEdit: true,
        invoice_id: formData.id
    });

    temDetail = null;
};
//费用删除
const onDel = async (index: number) => {
    formData.details!.splice(index, 1);
};
//费用表双击
const onDetailDbClick = (row: any) => {
    // console.log(row);
    if (row.isEdit) {
        return;
    }
    temDetail = {};

    Object.assign(temDetail, omit(row, ['isEdit']));
    row.isEdit = true;
};
// 费用确定
const onEdit = async (_index: number, row: InvoiceDetailModel) => {
    row.isEdit = false;
};
// 费用取消修改
const onCancel = (index: number, row: InvoiceDetailModel) => {
    if (isNil(temDetail)) {
        formData.details!.splice(index, 1);
    } else {
        Object.assign(row, temDetail);
        row.isEdit = false;
    }
};
</script>
<style lang="scss" scoped>
.invoiceform {
    margin-bottom: 20px;
    padding: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.detailtable {
    margin-bottom: 20px;
    padding-top: 10px 10px;
    border: solid 2px var(--el-color-primary);
    box-shadow: 10px 10px 5px rgba(100, 100, 100, 0.5);
}
.btn-group {
    .btn {
        margin-right: 5px;
    }
}
</style>
